package com.mission.schedule.add603;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.google.gson.Gson;
import com.mission.schedule.R;
import com.mission.schedule.add603.adapter.NewInformationAdapter;
import com.mission.schedule.add603.bean.UserNewLy;
import com.mission.schedule.applcation.App;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.db.DBHelper;
import com.mission.schedule.my160920.widget.OnRefreshRecyclerViewHeader;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

/**
 * Created by liwei on 2016/11/15.
 */

public class NewInformationActivity extends Activity {


    private LinearLayout top_ll_left,nones;
    private SwipeToLoadLayout toLoadLayout;
    private RecyclerView swipe_target;
    private NewInformationAdapter newInformationAdapter;
    SharedPrefUtil sharedPrefUtil = null;
    private String userID = "";
    private List<UserNewLy.ListBean> listBeanList = new ArrayList<>();
    private List<UserNewLy.DeListBean> deListBeanList = new ArrayList<>();
    private List<UserNewLy.TDeListBean> tDeListBeanList = new ArrayList<>();
    final ProgressUtil progressUtil = new ProgressUtil();
    private TextView myschedule_title, bj_ll;
    /**
     * 是否需要显示列表按钮
     */
    private boolean dateType = false;

    private NewInfor newInfor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.new_information);

        newInfor = new NewInfor();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("newinfor");
        registerReceiver(newInfor, intentFilter);

        sharedPrefUtil = new SharedPrefUtil(this, ShareFile.USERFILE);
        userID = sharedPrefUtil.getString(this, ShareFile.USERFILE,
                ShareFile.USERID, "0");
        myschedule_title = (TextView) findViewById(R.id.myschedule_title);
        top_ll_left = (LinearLayout) findViewById(R.id.ly_top_ll_left);
        nones = (LinearLayout) findViewById(R.id.nones);
        top_ll_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        bj_ll = (TextView) findViewById(R.id.bj_ll);
        bj_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myschedule_title.setText("消息列表");
                bj_ll.setVisibility(View.GONE);
                dateType = false;
                setAdapter();
            }
        });
        swipe_target = (RecyclerView) findViewById(R.id.swipe_target);
        swipe_target.setHasFixedSize(true);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        swipe_target.setLayoutManager(linearLayoutManager);
        swipe_target.setItemAnimator(new DefaultItemAnimator());

        toLoadLayout = (SwipeToLoadLayout) findViewById(R.id.newi_swip);
        OnRefreshRecyclerViewHeader header = (OnRefreshRecyclerViewHeader) findViewById(R.id.swipe_refresh_header);
//        toLoadLayout.setRefreshHeaderView(header);
        toLoadLayout.setRefreshEnabled(false);
//        toLoadLayout.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                DownNewInforMation();
//            }
//        });
//        swipe_target.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                int topRowVerticalPosition =
//                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
//                toLoadLayout.setRefreshEnabled(topRowVerticalPosition >= 0);
//            }
//
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//            }
//        });
        /**
         * 检查是否有发出的6.0.3版本的表,没有则创建(新消息表)
         */
        DBHelper helper = new DBHelper(this);
//        if (!helper.tabIsExist("CLCommentTable")){
//            App.getDBcApplication().createCLCommentTable();
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    DownNewInforMation();
//                }
//            },2000);
//        }else {
//            DownNewInforMation();
//        }

        if (getIntent().getIntExtra("type", 0) == 0) {
            myschedule_title.setText("消息列表");
            bj_ll.setVisibility(View.GONE);
            dateType = false;
            setAdapter();
        } else {
            myschedule_title.setText("新消息");
            bj_ll.setVisibility(View.VISIBLE);
            dateType = true;
            if (!helper.tabIsExist("CLCommentTable")) {
                App.getDBcApplication().createCLCommentTable();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        DownNewInforMation();
                    }
                }, 2000);
            } else {
                DownNewInforMation();
            }
        }

    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    setAdapter();
                    progressUtil.dismiss();
                    break;
                case 0:
                    Toast.makeText(NewInformationActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                    progressUtil.dismiss();
                    break;
            }
        }

    };

    private void sendMess(int what) {
        Message message = new Message();
        message.what = what;
        handler.sendMessage(message);
    }


    /**
     * 下载新信息
     */
    public void DownNewInforMation() {
        progressUtil.ShowProgress(this, true, true, "正在同步数据...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLConstants.HOST + "/appFrends_downUserNewLy.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();

                                UserNewLy userNewLy = gson.fromJson(result, UserNewLy.class);
                                Log.e("TAG", result);
                                if (userNewLy.status == 0) {

                                    listBeanList = userNewLy.list;
                                    deListBeanList = userNewLy.delList;

                                    if (listBeanList != null) {
                                        for (UserNewLy.ListBean bean : listBeanList) {
                                            App.getDBcApplication().insertNewInformationLy(bean);
                                        }
                                        if (deListBeanList != null) {
                                            for (UserNewLy.DeListBean bean : deListBeanList) {
                                                App.getDBcApplication().deleteNewInformationLy(bean.id);
                                            }
                                        }
                                    }
                                    sendMess(1);
                                } else {
                                    sendMess(0);
                                }
                                changeTime();
                            } catch (Exception e) {
                                e.printStackTrace();
                                sendMess(0);
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                sendMess(0);
                Log.d("TAG", "downUserNewLy---error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userID);// "52432"
                return map;
            }
        };
        stringRequest.setTag("downUserNewLy");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }


    /**
     * 修改总消息时间
     */
    public void changeTime() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLConstants.HOST + "/appFrends_addUserMessChangeTime.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "downUserNewLy---error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userID);// "52432"
                return map;
            }
        };
        stringRequest.setTag("downUserNewLy");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    @Override
    public void onBackPressed() {
        if (getIntent().getIntExtra("type", 0) == 0) {
            finish();
        } else {
            if (dateType == false) {
                myschedule_title.setText("新消息");
                bj_ll.setVisibility(View.VISIBLE);
                dateType = true;
                setAdapter();
            } else {
                finish();
            }
        }
    }

    List<UserNewLy.ListBean> listBeanArrayList = new ArrayList<>();

    private void setAdapter() {
        if (dateType == true) {
            setdate();
        } else {
            alldate();
        }
        newInformationAdapter = new NewInformationAdapter(this, nMap, userID, (dateType ? 0 : 1));
        swipe_target.setAdapter(newInformationAdapter);
        if (nMap.size() > 0){
            toLoadLayout.setVisibility(View.VISIBLE);
            nones.setVisibility(View.GONE);
        }else {
            nones.setVisibility(View.VISIBLE);
            toLoadLayout.setVisibility(View.GONE);
        }
    }

    List<Map<String, String>> nMap = new ArrayList<>();

    private void alldate() {
        listBeanArrayList.clear();
        nMap.clear();
        listBeanArrayList = App.getDBcApplication().getAllNewInformationLy(userID);
        for (int i = 0; i < listBeanArrayList.size(); i++) {
            Map<String, String> map = new HashMap<>();
            map.put("uid", listBeanArrayList.get(i).uid);
            map.put("opTime", listBeanArrayList.get(i).opTime);
            map.put("U_BACKGROUND_IMAGE", listBeanArrayList.get(i).U_BACKGROUND_IMAGE);
            map.put("calendarId", listBeanArrayList.get(i).calendarId);
            map.put("remark", listBeanArrayList.get(i).remark);
            map.put("changeTime", listBeanArrayList.get(i).changeTime);
            map.put("mess", listBeanArrayList.get(i).mess);
            map.put("remark1", listBeanArrayList.get(i).remark1);
            map.put("cType", listBeanArrayList.get(i).cType + "");
            map.put("remark2", listBeanArrayList.get(i).remark2 + "");
            map.put("id", listBeanArrayList.get(i).id + "");
            map.put("schId", listBeanArrayList.get(i).schId);
            map.put("U_NICK_NAME", listBeanArrayList.get(i).U_NICK_NAME);
            map.put("U_PORTRAIT", listBeanArrayList.get(i).U_PORTRAIT);
            map.put("cId", listBeanArrayList.get(i).cId);
            map.put("num", "-1");
            map.put("newtype", "1");
            nMap.add(map);
        }
    }

    private void setdate() {
        listBeanArrayList.clear();
        nMap.clear();

        listBeanArrayList = App.getDBcApplication().getNewInformationLy("",userID);

        //去重
        if (listBeanArrayList.size() > 0) {
//            if (listBeanArrayList.size() > 1) {
//                for (int i = listBeanArrayList.size() - 1; i > 0; i--) {
//                    for(int j = i - 1; j >= 0; j--) {
//                        if (listBeanArrayList.get(j).calendarId.equals(listBeanArrayList.get(i).calendarId)) {
//                            listBeanArrayList.remove(i);
//                        }
//                    }
//                }
//            }
            LinkedHashSet<UserNewLy.ListBean> set = new LinkedHashSet<>(listBeanArrayList);
            listBeanArrayList.clear();
            listBeanArrayList.addAll(set);
            for (int i = 0; i < listBeanArrayList.size(); i++) {
                Map<String, String> map = new HashMap<>();
                List<UserNewLy.ListBean> listBeanList1 = App.getDBcApplication().getNewInformationLy(listBeanArrayList.get(i).calendarId,userID);
                map.put("uid", listBeanList1.get(0).uid);
                map.put("opTime", listBeanList1.get(0).opTime);
                map.put("U_BACKGROUND_IMAGE", listBeanList1.get(0).U_BACKGROUND_IMAGE);
                map.put("calendarId", listBeanList1.get(0).calendarId);
                map.put("remark", listBeanList1.get(0).remark);
                map.put("changeTime", listBeanList1.get(0).changeTime);
                map.put("mess", listBeanList1.get(0).mess);
                map.put("remark1", listBeanList1.get(0).remark1);
                map.put("cType", listBeanList1.get(0).cType + "");
                map.put("remark2", listBeanList1.get(0).remark2 + "");
                map.put("id", listBeanList1.get(0).id + "");
                map.put("schId", listBeanList1.get(0).schId);
                map.put("U_NICK_NAME", listBeanList1.get(0).U_NICK_NAME);
                map.put("U_PORTRAIT", listBeanList1.get(0).U_PORTRAIT);
                map.put("cId", listBeanList1.get(0).cId);
                map.put("num", listBeanList1.size() + "");
                map.put("newtype", listBeanList1.get(0).newtype + "");
                nMap.add(map);
            }
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (newInfor != null) {
            unregisterReceiver(newInfor);
        }
    }

    class NewInfor extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getIntExtra("l", 0) == 1) {
                setAdapter();
            }
        }
    }

}
